package com.tanhua.test;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.MongoAppilcation;
import com.tanhua.model.mongo.Movement;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Collection;
import java.util.List;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/3 13:48
 */
@SpringBootTest(classes = MongoAppilcation.class)
@RunWith(SpringRunner.class)
public class RandomMovement {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void random(){
        // 随机查询方法， 百度
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("userId").ne(106)),
                Aggregation.sample(20)
        );
        AggregationResults<Movement> results = mongoTemplate.aggregate(agg, Movement.class, Movement.class);
        List<Movement> movements = results.getMappedResults();
        List<Long> userId = CollectionUtil.getFieldValues(movements, "userId", Long.class);
        System.out.println(userId);
    }
}
